<template>
  <el-dialog
    v-model="visible"
    title="导入表"
    width="950px"
    top="5vh"
    append-to-body
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form ref="queryRef" :model="queryParams" :inline="true">
      <el-form-item label="数据源" prop="dataSourceId">
        <el-select
          v-model="queryParams.dataSourceId"
          placeholder="请选择数据源"
          filterable
          @change="handleQuery"
        >
          <el-option
            v-for="item in dataSourceIdOptions"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="表名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入表名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表描述" prop="comment">
        <el-input
          v-model="queryParams.comment"
          placeholder="请输入表描述"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="list"
      height="360px"
      @row-click="clickRow"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="表名称" />
      <el-table-column prop="comment" label="表描述" />
      <el-table-column label="更新时间">
        <template #default="{ row }">
          {{ row.updateTime || row.createTime }}
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      v-model:page="pageParams.pageNum"
      v-model:limit="pageParams.pageSize"
      :total="total"
      @pagination="getList"
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="submitLoading" @click="handleImportTable"
          >确 定
        </el-button>
        <el-button @click="visible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
  import { ref, computed, watch, defineProps, defineEmits } from 'vue';
  import { listDbTable, importTable } from '@/api/web/bu/form';
  import modal from '@/plugins/modal';

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    dataSourceIdOptions: {
      type: Array,
      default: () => [],
    },
  });
  const emits = defineEmits(['update:modelValue', 'success']);

  const visible = computed({
    set(v) {
      emits('update:modelValue', v);
    },
    get() {
      return props.modelValue;
    },
  });

  const total = ref(0);
  const tables = ref([]);
  const loading = ref(false);
  const submitLoading = ref(false);
  const list = ref([]);
  const queryRef = ref(null);
  const tableRef = ref(null);
  const pageParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const queryParams = ref({
    dataSourceId: null,
    name: null,
    comment: null,
  });

  watch(visible, (v) => {
    if (v) {
      const one = props.dataSourceIdOptions?.[0];
      if (one) {
        queryParams.value.dataSourceId = one.value;
        getList();
      } else {
        modal.msgWarning('暂无数据源');
      }
    }
  });

  function clickRow(row) {
    tableRef.value?.toggleRowSelection(row);
  }

  function handleSelectionChange(selection) {
    tables.value = selection.map((item) => item.name);
  }

  function getList() {
    loading.value = true;
    listDbTable(pageParams.value, queryParams.value)
      .then((res) => {
        list.value = res?.data?.records ?? [];
        total.value = res?.data?.total ?? 0;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  function handleQuery() {
    pageParams.value.pageNum = 1;
    getList();
  }

  function resetQuery() {
    queryRef.value?.resetFields();
    handleQuery();
  }

  function handleImportTable() {
    if (tables.value.length === 0) {
      modal.msgError('请选择要导入的表');
      return;
    }
    if (tables.value.length !== 1) {
      modal.msgError('一次只能选一个表');
      return;
    }

    const params = {
      tableName: tables.value[0],
      dataSourceId: queryParams.value.dataSourceId,
    };
    submitLoading.value = true;
    importTable(params)
      .then((res) => {
        modal.msgSuccess(res.msg);
        if (res.code === 200) {
          visible.value = false;
          emits('success');
        }
      })
      .finally(() => {
        submitLoading.value = false;
      });
  }

  function handleClosed() {
    total.value = 0;
    tables.value = [];
    loading.value = false;
    submitLoading.value = false;
    list.value = [];
    pageParams.value = {
      pageNum: 1,
      pageSize: 10,
    };
    queryParams.value = {
      dataSourceId: null,
      name: null,
      comment: null,
    };
  }
</script>
